﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelperFromTheSkeleton.Model.WebSocketModels
{
    public class WebSocketChannelModel
    {
        private Func<string, Task<bool>>? _sendfunc;
        private Func<bool>? _isClose;
        private Func<Task>? _closeFunc;

        public Guid ChannelID { get; set; }

        public WebSocketChannelModel(Func<string, Task<bool>> sendfunc, Func<bool> isClose, Func<Task> closeFunc)
        {
            _sendfunc = sendfunc;
            _isClose = isClose;
            _closeFunc = closeFunc;
            ChannelID = Guid.NewGuid();
        }

        public async Task<bool> Send(string text)
        {
            if (!_isClose?.Invoke() ?? true)
            {
                if (_sendfunc == null) return false;
                return await _sendfunc.Invoke(text);
            }
            return true;
        }

        public void AddCloseFunc(Func<Task> closeFunc)
        {
            _closeFunc += closeFunc;
        }

        public async Task Close()
        {
            _sendfunc = null;
            _isClose = null;
            if (_closeFunc == null) return;
            await _closeFunc.Invoke();
        }
    }
}
